<?php

namespace app\shop\controller\collect;

use app\common\model\collect\GoodsAttributeModel;
use app\common\model\collect\GoodsImageModel;
use app\common\model\collect\GoodsClaimLogModel;
use app\common\model\collect\GoodsModel;
use app\common\model\collect\GoodsSkuModel;
use app\common\model\shop\CurrencyModel;
use app\common\model\shop\GoodsModel as ShopGoodsModel;
use app\common\model\shop\PlatformModel;
use app\common\model\shop\ShopsModel;
use think\admin\Controller;
use think\admin\helper\QueryHelper;
use think\admin\model\SystemUser;
use think\facade\Db;
use think\facade\Validate;

/**
 * 采集商品管理
 *
 * @Description 商品管理
 * @package app\shop\controller\collect
 * @author wangqinghui
 * @date 2024-10-17 10:55
 */
class Goods extends Controller
{
    /**
     * 商品列表
     * @auth true
     * @menu true
     * @author wangqinghui
     * @date 2024-10-17 13:37
     */
    public function index()
    {
        $this->type = $this->request->get('type', '');

        GoodsModel::mQuery()->layTable(function () {
            $this->title = '采集商品管理';
            // 订单来源
            $this->from_arr    = GoodsModel::from_arr();
            // 用户列表
            $user_list = SystemUser::getUserList($this->account_id, SystemUser::getNoTeacherUserType());
            $this->system_user = array_column($user_list, 'nickname', 'id');

            $this->type_arr = ['all'=>lang('全部'), 'no'=>lang('未认领'), 'yes'=>lang('已认领')];

        }, function (QueryHelper $query) {

            $type = $this->request->get('type', '');
            if(!empty($type) && in_array($type, ['no', 'yes'])){
                $query->where('is_claim', $type == 'yes');
            }

            $query->where(['is_deleted' => 0]);

            $query->like('title,collect_url,shop_name')->equal('account_id,from,user_id,update_user_id,goods_code,spu_code')->dateBetween('create_at,update_at');
            $query->order('id desc');
        });
    }

    /**
     * _index_page_filter
     *
     * @Description 格式化列表数据
     * @author wangqinghui
     * @date 2024-10-19 11:00
     * @param array $data
     * @return void
     */
    protected function _index_page_filter(array &$data)
    {
        if(!empty($data)){

            // 获取采集来源
            $from_arr = GoodsModel::from_arr();

            // 用户列表
            $user_ids = array_merge(array_column($data, 'user_id'), array_column($data, 'update_user_id'));
            $system_user = SystemUser::mk()->where('id', 'in', $user_ids)->column('nickname', 'id');

            // 获取认领平台信息
            $goods_id_arr     = array_column($data, 'id');
            $goods_claim_list = GoodsClaimLogModel::mk()->where('collect_goods_id', 'in', $goods_id_arr)->select()->toArray();
            $goods_claim_data = [];
            if(!empty($goods_claim_list)){
                $platform_ids = array_column($goods_claim_list, 'platform_id');
                $platform_data = PlatformModel::mk()->where('id', 'in', $platform_ids)->column('id,title', 'id');
                foreach ($goods_claim_list as $key => $value){
                    $goods_claim_data[$value['collect_goods_id']][] = !empty($platform_data[$value['platform_id']]['title']) ? $platform_data[$value['platform_id']]['title'] : '';
                }
            }

            foreach ($data as $key => &$value){
                // 采集来源
                $value['from_text'] = $from_arr[$value['from']] ?? '-';
                // 采集人
                $value['user_id_text'] = $system_user[$value['user_id']] ?? '-';
                // 更新人
                $value['update_user_text'] = $system_user[$value['update_user_id']] ?? '-';
                // 认领平台
                $value['claim_platform'] = !empty($goods_claim_data[$value['id']]) ? array_unique($goods_claim_data[$value['id']]) : [];
            }
        }
    }

    /**
     * 编辑商品
     * @auth true
     */
    public function edit()
    {
        $data = $this->request->param();

        if ($this->request->isPost()){

            $rule = [
                "id|商品id" =>  "require|integer",
                "title|产品标题" =>  "require|max:255",
                "specData|产品规格" =>  "require|array",
                "skus|SKU" =>  "require|array",
                "desc|简单描述" =>  "require",
                "detail|详细描述" =>  "require",
            ];
            $validate = Validate::rule($rule);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            // 更新人
            $data['update_user_id'] = $this->adminUser['id'];
            // 主图
            $data['main_pic'] = explode('|',$data['goods_images'])[0] ?? '';

            // 商品价格范围
            $data['min_price'] = min(array_column($data['skus'], 'price'));
            $data['max_price'] = max(array_column($data['skus'], 'price'));

            $goods_images = [];
            if(!empty($data['goods_images'])){
                // 处理图片
                foreach (explode('|',$data['goods_images']) as $v){
                    $goods_images[] = [
                        'goods_id' => $data['id'],
                        'image' => $v,
                    ];
                }
            }

            // 处理规格
            $specData = [];
            foreach ($data['specData'] as $v){
                foreach ($v['child'] as $vv){
                    $specData[] = [
                        'goods_id' => $data['id'],
                        'key_name' => $v['title'],
                        'value_name' => $vv['title'],
                        'checked' => ($vv['checked'] == 'true' || $vv['checked'] == '1') ? 1 : 0,
                    ];
                }
            }

            // 处理sku

            try {
                // 启动事务
                Db::startTrans();

                // 更新商品
                GoodsModel::mq()->strict(false)->update($data);
                // 删除图片
                GoodsImageModel::mq()->where(['goods_id'=>$data['id']])->delete();
                // 添加图片
                GoodsImageModel::mq()->insertAll($goods_images);
                // 删除规格
                GoodsAttributeModel::mq()->where(['goods_id'=>$data['id']])->delete();
                // 添加规格
                $specTitleId = []; // 规格值=》id 对应关系
                foreach ($specData as $v){
                    $specTitleId[$v['value_name']] = GoodsAttributeModel::mq()->insertGetId($v);
                }
                // 删除skus
                GoodsSkuModel::mq()->where(['goods_id'=>$data['id']])->delete();
                // 组装sku数据
                $goods_skus = [];
                foreach ($data['skus'] as $k => $v){
                    // 处理attribute_ids
                    $attribute_ids_arr = explode(',',$k);
                    foreach ($attribute_ids_arr as &$attribute_v){
                        $attribute_v = $specTitleId[$attribute_v] ?? '';
                    }
                    $attribute_ids = implode(',',$attribute_ids_arr);

                    $goods_skus[] = [
                        'title' => $v['title'],
                        'goods_id' => $data['id'],
                        'image' => $v['image'],
                        'price' => $v['price'],
                        'length' => $v['length'],
                        'width' => $v['width'],
                        'height' => $v['height'],
                        'weight' => $v['weight'],
                        'volume' => round($v['length'] * $v['width'] * $v['height'],3),
                        'attribute_titles' => $k,
                        'attribute_ids' => $attribute_ids,
                    ];
                }

                // 添加skus
                GoodsSkuModel::mq()->insertAll($goods_skus);

//                Db::rollback();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 0, 'info' => $e->getMessage()]);
            }
            $this->success('保存成功');

        }

        // 商品基本信息
        $GoodsInfo = GoodsModel::mq()->where(['id'=>$data['id']])->find()->toArray();
        //  商品规格
        $GoodsImages = GoodsImageModel::mq()->where(['goods_id'=>$data['id']])->column('image');
        $GoodsInfo['goods_images'] = implode('|',$GoodsImages);
//        halt($GoodsInfo['goods_images']);
        //  商品规格
        $specData = GoodsAttributeModel::mq()->where(['goods_id'=>$data['id']])->select()->toArray();
        // 处理结构
        $specDataTree = [];
        foreach ($specData as $k => $v){
            $specDataTree[$v['key_name']]['id'] = $v['key_name'];
            $specDataTree[$v['key_name']]['title'] = $v['key_name'];
            $specDataTree[$v['key_name']]['child'][] = [
                'id' => $v['value_name'],
                'title' => $v['value_name'],
                'checked' => $v['checked'],
            ];
        }
//        halt($specDataTree);
        $specDataTree = array_values($specDataTree);
        // skus todo
        $goods_skus = GoodsSkuModel::mq()->where(['goods_id'=>$data['id']])->select()->toArray();
        $goods_skus_data = [];
        foreach ($goods_skus as $v){
            $goods_skus_data["skus[" . $v['attribute_titles'] . "][image]"] = $v['image'];
            $goods_skus_data["skus[" . $v['attribute_titles'] . "][title]"] = $v['title'];
            $goods_skus_data["skus[" . $v['attribute_titles'] . "][price]"] = $v['price'];
            $goods_skus_data["skus[" . $v['attribute_titles'] . "][length]"] = $v['length'];
            $goods_skus_data["skus[" . $v['attribute_titles'] . "][width]"] = $v['width'];
            $goods_skus_data["skus[" . $v['attribute_titles'] . "][height]"] = $v['height'];
        }
        $this->assign([
            'vo' => $GoodsInfo,
            'specDataTree' => json_encode($specDataTree,320),
            'goods_skus_data' => json_encode($goods_skus_data,320),
        ]);
        $this->fetch();

    }

    /**
     * 删除商品
     *
     * @Description 删除商品
     * @auth true
     * @return void
     * @author wangqinghui
     * @date 2024-10-17 13:55
     */
    public function remove ()
    {
        GoodsModel::mDelete();
    }


    /**
     * 认领
     *
     * @Description
     * @auth true
     * @author wangqinghui
     * @date 2024-11-01 11:00
     * @return void
     */
    public function claim()
    {
        if($this->request->isPost()){
            $post_data = $this->request->post('data');
            $post_data = !empty($post_data) ? json_decode($post_data, 1): [];
            $rule = [
                'stock|默认库存'    =>  'require|integer|between:1,1000000',
                'shop|目标店铺'     =>  'require|array',
                'ids|商品id'        =>  'require'
            ];
            $validate = Validate::rule($rule);
            if(!$validate->check($post_data)){
                $this->error($validate->getError());
            }
            $goods_id_arr = explode(',', $post_data['ids']);
            if(empty($goods_id_arr)){
                $this->error('操作商品信息有误');
            }

            // 获取商品信息
            $map = [
                ['id', 'in', $goods_id_arr],
                ['is_deleted', '=', 0]
            ];
            $goods_list = GoodsModel::mk()->where($map)->column('id,collect_url,spu_code,title,desc,detail,main_pic,shop_name', 'id');
            if(empty($goods_list)){
                $this->error('操作商品信息有误');
            }
            // 获取商品属性信息
            $map = [
                ['goods_id', 'in', $goods_id_arr],
            ];
            // 获取商品图片
            $goods_image_data = GoodsImageModel::mk()->where($map)->select()->toArray();
            // 获取商品属性信息
            $goods_attribute_data = GoodsAttributeModel::mk()->where($map)->select()->toArray();
            // 获取商品sku信息
            $goods_sku_data = GoodsSkuModel::mk()->field('sku_code,title,goods_id,image,price,length,width,height,weight,volume,attribute_ids,attribute_titles')->where($map)->select()->toArray();

            // 获取店铺平台信息
            $platform_ids = array_keys($post_data['shop']);
            $platform_data = PlatformModel::mk()->where('id', 'in', $platform_ids)->column('code,title', 'id');

            // 获取店铺信息
            $shop_ids = array_reduce($post_data['shop'], function($carry, $item) {
                return array_merge($carry, $item);
            }, []);
            $shop_data = ShopsModel::mk()->where('id', 'in', $shop_ids)->column('name,currency_id,account_id', 'id');

            // 获取币种信息
            $currency_ids = array_column($shop_data, 'currency_id');
            $currency_data = [];
            if(!empty($currency_ids)){
                $map = [
                    ['id',  'in',   $currency_ids]
                ];
                $currency_data = CurrencyModel::mk()->where($map)->column('currency_name,symbol,exchange_rate', 'id');
            }

            // 获取商品是否已经认领过
            $claim_log_list = GoodsClaimLogModel::mk()->where('collect_goods_id', 'in', $goods_id_arr)->select()->toArray();
            if(!empty($claim_log_list)){
                foreach ($claim_log_list as $key => $value) {
                    if(in_array($value['collect_goods_id'], $goods_id_arr)){
                        foreach ($post_data['shop'] as $k => $v) {
                            if(in_array($value['shop_id'], $shop_ids)){
                                $g_title = !empty($goods_list[$value['collect_goods_id']]['title']) ? $goods_list[$value['collect_goods_id']]['title'] : '';
                                $g_platform = !empty($platform_data[$k]['title']) ? $platform_data[$k]['title'] : '';
                                $g_shop = !empty($shop_data[$value['shop_id']]['name']) ? $shop_data[$value['shop_id']]['name'] : '';
                                $this->error('商品:'.$g_title.'已经认领过了,'.$g_platform.':'.$g_shop);
                            }
                        }
                    }
                }
            }

            // 启动事务
            Db::startTrans();
            try {
                // 认领商品到平台店铺
                $add_clain_log = [];
                foreach ($post_data['shop'] as $key => $value) {
                    if(!empty($value) && is_array($value)){
                        $platform_code = !empty($platform_data[$key]['code']) ? $platform_data[$key]['code'] : '';
                        if(empty($platform_code)){
                            throw new \Exception($platform_data[$key]['title'].'平台店铺信息有误');
                        }
                        list($goods_model, $goods_sku_model, $goods_attr_model, $goods_image_model) = ShopGoodsModel::instance($key);
                        if(empty($goods_model) || empty($goods_sku_model) || empty($goods_attr_model) || empty($goods_image_model)){
                            throw new \Exception($platform_data[$key]['title'].'平台商品不存在');
                        }

                        // 循环平台下的店铺
                        foreach ($value as $k => $v) {
                            // 店铺信息
                            $shop_info = !empty($shop_data[$v]) ? $shop_data[$v] : [];
                            // 店铺汇率
                            $currenct_rate = !empty($currency_data[$shop_info['currency_id']]['exchange_rate'])? $currency_data[$shop_info['currency_id']]['exchange_rate'] : 0;
                            // 同步商品到店铺
                            foreach ($goods_list as $goods_key => $goods_value) {
                                // 同步商品数据
                                $add_goods_data = [
                                    'user_id'       =>  $this->adminUser['id'] ?? 0,// 用户ID
                                    'account_id'    =>  $shop_info['account_id'] ?? 0,// 公司ID
                                    'collect_goods_id'  =>  $goods_value['id'] ?? 0,// 采集商品ID
                                    'spu_code'      =>  $goods_model->createSPU(),// 商品SPU编码
                                    'title'         =>  $goods_value['title'] ?? '',// 商品标题
                                    'origional_title' => $goods_value['title'] ?? '',// 原始标题
                                    'short_desc'    =>  $goods_value['desc'] ?? '',// 商品描述
                                    'origional_short_desc' => $goods_value['desc'] ?? '',// 原始描述
                                    'long_desc'     =>  $goods_value['detail'] ?? '',// 商品详情
                                    'origional_long_desc' => $goods_value['detail'] ?? '',// 原始详情
                                    'shop_id'       =>  $v ?? 0,// 店铺ID
                                    'mode_type'     =>  1,// sku类型 0单品 1多规格
                                    'source_url'    =>  $goods_value['collect_url'] ?? '',// 商品来源链接
                                    'main_pic'      =>  $goods_value['main_pic'] ?? '',// 主图
                                    'from_type'     =>  1,// 来源类型 1数据采集 2手工录入
                                    'supplier_name' =>  $goods_value['shop_name'] ?? '',// 供应商
                                ];
                                $goods_id = $goods_model->insertGetId($add_goods_data);
                                if(empty($goods_id) || ($goods_id <= 0)){
                                    throw new \Exception($platform_data[$key]['title'].':'.($shop_data[$v]['name'] ?? '').'同步商品数据失败');
                                }
                                // 插入商品图片
                                if(!empty($goods_image_data)){
                                    $image_data = [];
                                    foreach ($goods_image_data as $image_key => $image_value) {
                                        if($image_value['goods_id'] != $goods_value['id']){
                                            continue;
                                        }
                                        $image_data[] = [
                                            'goods_id'      =>  $goods_id,
                                            'image'         =>  $image_value['image'],
                                        ];
                                    }
                                    if(!empty($image_data)){
                                        $image_count = $goods_image_model->insertAll($image_data);
                                        if(empty($image_count) || ($image_count <= 0)){
                                            throw new \Exception($platform_data[$key]['title'].':'.($shop_data[$v]['name'] ?? '').'同步商品图片数据失败');
                                        }
                                    }
                                }

                                // 插入商品属性数据
                                $old_attr_list = [];
                                if(!empty($goods_attribute_data)){
                                    $attr_data = [];
                                    foreach ($goods_attribute_data as $attr_key => $attr_value) {
                                        if($attr_value['goods_id'] != $goods_value['id']){
                                            continue;
                                        }
                                        $attr_data[] = [
                                            'goods_id'      =>  $goods_id,
                                            'key_name'  =>  $attr_value['key_name'],
                                            'origional_key_name'  =>  $attr_value['key_name'],
                                            'value_name'  =>  $attr_value['value_name'],
                                            'origional_value_name'  =>  $attr_value['value_name'],
                                            'image'        =>  $attr_value['image'],
                                            'checked'       =>  $attr_value['checked'],
                                        ];
                                        // 获取老属性对应关系
                                        $old_attr_list[$attr_value['id']] = $attr_value['key_name'].'-'.$attr_value['value_name'];
                                    }
                                    if(!empty($attr_data)){
                                        $attr_count = $goods_attr_model->insertAll($attr_data);
                                        if(empty($attr_count) || ($attr_count <= 0)){
                                            throw new \Exception($platform_data[$key]['title'].':'.($shop_data[$v]['name'] ?? '').'同步商品属性数据失败');
                                        }
                                    }
                                }
                                // 插入商品sku
                                if(!empty($goods_sku_data)){
                                    // 获取商品属性
                                    $new_attr_list = $goods_attr_model->where('goods_id', $goods_id)->select()->toArray();
                                    $new_attr_data = [];
                                    foreach ($new_attr_list as $n_attr_key => $n_attr_value) {
                                        $new_attr_data[$n_attr_value['key_name'].'-'.$n_attr_value['value_name']] = $n_attr_value['id'];
                                    }

                                    $sku_data = [];
                                    $sku_count = 0;
                                    foreach ($goods_sku_data as $sku_key => $sku_value) {
                                        if($sku_value['goods_id'] != $goods_value['id']){
                                            continue;
                                        }
                                        $old_attr_ids = explode(',', $sku_value['attribute_ids']);
                                        $new_attr_ids = [];
                                        if(!empty($old_attr_ids)){
                                            foreach ($old_attr_ids as $o_attr_key => $o_attr_value) {
                                                if(empty($new_attr_data[$old_attr_list[$o_attr_value]])){
                                                    continue;
                                                }
                                                $new_attr_ids[] = $new_attr_data[$old_attr_list[$o_attr_value]];
                                            }
                                        }
                                        $sku_title = $add_goods_data['spu_code'].'-'.$sku_value['attribute_titles'];
                                        $temp_sku = [
                                            'goods_id'      =>  $goods_id,
                                            'title'         =>  $sku_title,// sku标题
                                            'sku_code'      =>  $sku_value['sku_code'],// sku编码
                                            'image'         =>  $sku_value['image'],// sku图片
                                            'price'         =>  bcdiv($sku_value['price'], $currenct_rate, 4),// 价格
                                            'length'        =>  $sku_value['length'],// 长度
                                            'width'         =>  $sku_value['width'],// 宽度
                                            'height'        =>  $sku_value['height'],// 高度
                                            'weight'        =>  $sku_value['weight'],// 重量(g)
                                            'volume'        =>  $sku_value['volume'],// 体积(cm³)
                                            'attribute_ids' =>  implode(',', $new_attr_ids),// 规格属性ID
                                            'stock'         =>  $post_data['stock'],// 库存
                                            'attribute_titles'  =>  $sku_value['attribute_titles'],// 规格属性集合
                                            'origional_attribute_titles'  =>  $sku_value['attribute_titles'],// 原始规格属性集合
                                            'sale_price'    =>  bcdiv($sku_value['price'], $currenct_rate, 4),// 销售价
                                            'currency_id'   =>  $shop_info['currency_id'] ?? 0,// 币种ID
                                            'currency_rate' =>  $currenct_rate,// 汇率
                                        ];
                                        switch ($platform_code) {
                                            case PlatformModel::OZON_CODE:
                                                $temp_sku['goods_nu'] = $add_goods_data['spu_code'].'_'.++$sku_count;// sku
                                                break;
                                            case PlatformModel::SELF_CODE:
                                                $temp_sku['barcode'] = $add_goods_data['spu_code'].'_'.++$sku_count;// sku
                                                unset($temp_sku['currency_id'], $temp_sku['currency_rate']);
                                                break;
                                            default:
                                                break;
                                        }
                                        $sku_data[] = $temp_sku;
                                    }
                                    if(!empty($sku_data)){
                                        $sku_count = $goods_sku_model->insertAll($sku_data);
                                        if(empty($sku_count) || ($sku_count <= 0)){
                                            throw new \Exception($platform_data[$key]['title'].':'.($shop_data[$v]['name'] ?? '').'同步商品sku数据失败');
                                        }
                                    }
                                }

                                // 插入认领记录
                                $add_clain_log[] = [
                                    'goods_id'          =>      $goods_id,
                                    'shop_id'           =>      $v ?? 0,// 店铺ID
                                    'platform_id'       =>      $key ?? 0,// 平台ID
                                    'collect_goods_id'  =>      $goods_value['id'] ?? 0,// 采集商品ID
                                    'user_id'           =>      $this->adminUser['id'] ?? 0,// 认领用户ID
                                    'account_id'        =>      $this->adminUser['account_id'] ?? 0,// 公司ID
                                ];
                            }
                        }
                    }
                }

                // 增加商品认领记录
                if(!empty($add_clain_log)){
                    $count = GoodsClaimLogModel::mk()->insertAll($add_clain_log);
                    if($count <= 0){
                        throw new \Exception('增加认领记录失败');
                    }
                }

                // 更新商品认领状态
                $count = GoodsModel::mk()->where('id', 'in', $goods_id_arr)->update(['is_claim' => 1]);
                if($count < 0){
                    throw new \Exception('更新认领状态失败');
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error('认领失败:'.$e->getMessage());
            }
            $this->success('认领成功');
        }else{
            // 获取商品信息
            $goods_ids = $this->request->get('id', '');
            if(empty($goods_ids)){
                $this->error('商品信息有误');
            }
            // 获取平台信息
            $map = [
                ['status',      '=',    1]
            ];
            $platform_data = PlatformModel::mk()->where($map)->column('title', 'id');
            $platform_ids = array_keys($platform_data);
            // 获取授权的店铺
            $map = [
                ['is_deleted',  '=',    0],
                ['status',      '=',    1],
                ['platform_id', 'in',    $platform_ids],
            ];
            if(!$this->super){
                $map[] = ['account_id',     '=',    $this->adminUser['account_id']];
                $map[] = ['user_id',     '=',    $this->adminUser['id']];
            }
            $shop_list = ShopsModel::mk()->field('id,name,status,platform_id')->where($map)->select()->toArray();
            $shop_data = [];
            if(!empty($shop_list)){
                foreach ($shop_list as $key => $value){
                    $shop_data[$value['platform_id']]['id'] = $value['platform_id'];
                    $shop_data[$value['platform_id']]['name'] = $platform_data[$value['platform_id']]?? '';
                    $shop_data[$value['platform_id']]['sub_data'][] = $value;
                }
            }
            $this->fetch('claim', ['shop_data' => $shop_data, 'good_ids' => $goods_ids]);
        }
    }
}